package com.example.base.base.util

import android.app.Activity
import android.os.Handler
import android.os.Looper
import androidx.fragment.app.Fragment

/**
 *  全局的回调到UI线程
 */
fun <T> T.postUI(action: () -> Unit) {

    // Fragment
    if (this is Fragment) {
        val fragment = this
        if (!fragment.isAdded) return

        val activity = fragment.activity ?: return
        if (activity.isFinishing) return

        activity.runOnUiThread(action)
        return
    }

    // Activity
    if (this is Activity) {
        if (this.isFinishing) return

        this.runOnUiThread(action)
        return
    }

    // 主线程
    if (Looper.getMainLooper() === Looper.myLooper()) {
        action()
        return
    }

    // 子线程，使用handler
    Handler(Looper.getMainLooper()).post {
        action()
    }

}